package kr.hkit.summary_java.erp;

import java.awt.BorderLayout;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingConstants;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumnModel;

import kr.hkit.myframework.db.ConnectionFactory;
import kr.hkit.myframework.db.DbUtil;

public class PrnEmp extends JPanel {
	private JTable table;
	private Connection con = ConnectionFactory.getConnection();
	private ResultSet rs;
	private PreparedStatement pstmt;
	private JScrollPane scrollPane;

	/**
	 * Create the panel.
	 */
	public PrnEmp() {
		initialize();
		try {
			inputDb();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		tableCellAlginAndWidth();
	}

	private void inputDb() throws SQLException {
		DefaultTableModel model = (DefaultTableModel) table.getModel();
		String sql = "select e1.empno, e1.empname, c.titlename, e2.empname, e1.salary, d.deptname "
				+ "from department d, codetitle c, employee e1 "
				+ "left outer join employee e2 on e1.manager = e2.empno "
				+ "where titleno = e1.title and e1.dno = deptno;";
		pstmt = con.prepareStatement(sql);
		rs = pstmt.executeQuery();
		Object[] newRow = null;
		while (rs.next()) {
			newRow = new Object[] { rs.getInt(1), rs.getString(2),
					rs.getString(3), rs.getString(4), rs.getInt(5),
					rs.getString(6) };
			model.addRow(newRow);
		}
		DbUtil.close(con);
		DbUtil.close(pstmt);
		DbUtil.close(rs);
	}

	private void initialize() {
		setLayout(new BorderLayout(0, 0));

		scrollPane = new JScrollPane();
		add(scrollPane, BorderLayout.NORTH);

		table = new JTable();
		table.setModel(new DefaultTableModel(new Object[][] {}, new String[] {
				"사원번호", "사원명", "직급", "직속상관", "월급", "부서" }));
		scrollPane.setViewportView(table);
	}

	private void tableCellAlginAndWidth() {
		DefaultTableCellRenderer dtcrCenter = new DefaultTableCellRenderer();
		dtcrCenter.setHorizontalAlignment(SwingConstants.CENTER);

		TableColumnModel cModel = table.getColumnModel();

		cModel.getColumn(0).setPreferredWidth(70);
		cModel.getColumn(0).setCellRenderer(dtcrCenter);

		cModel.getColumn(1).setPreferredWidth(70);
		cModel.getColumn(1).setCellRenderer(dtcrCenter);

		cModel.getColumn(2).setPreferredWidth(70);
		cModel.getColumn(2).setCellRenderer(dtcrCenter);

		cModel.getColumn(3).setPreferredWidth(70);
		cModel.getColumn(3).setCellRenderer(dtcrCenter);

		cModel.getColumn(4).setPreferredWidth(70);
		cModel.getColumn(4).setCellRenderer(dtcrCenter);

		cModel.getColumn(5).setPreferredWidth(70);
		cModel.getColumn(5).setCellRenderer(dtcrCenter);
	}

}
